//
//  WBRootViewController.swift
//  CFZWeiBo
//
//  Created by Cedric Zheng on 23/11/2016.
//  Copyright © 2016 Cedric Zheng. All rights reserved.
//

import UIKit

class WBRootViewController: UIViewController {
    
    lazy var tableView: UITableView = UITableView(frame: self.view.bounds, style: .plain)
    
    var visitorView: WBVisitorView?
    
    lazy var refreshControl: UIRefreshControl = {
        let refresh = UIRefreshControl()
        refresh.addTarget(self, action: #selector(loginSuccess), for: .valueChanged)
        return refresh
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        defaultNotiCenter.addObserver(self, selector: #selector(loginSuccess), name: loginSuccessNotification.name, object: nil)
        
        setupUI()
    }
    
    deinit {
        defaultNotiCenter.removeObserver(self)
    }
}

// MARK: - Setup methods
extension WBRootViewController {
    func setupUI () {
        setupTableView()
        
        if !WBUserAccount.shared.hasLogin {
            setupVisitorView()
        }
    }
    
    func setupTableView () {
        view.addSubview(tableView)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.allowsSelection = false
    }
    
    func setupVisitorView () {
        visitorView = WBVisitorView(frame: self.view.bounds)
        visitorView?.delegate = self
        view.addSubview(visitorView!)
    }
}

// MARK: - Private methods
extension WBRootViewController {
    @objc fileprivate func loginSuccess() {
        visitorView?.removeFromSuperview()
        visitorView = nil
        
        loadData()
    }
    
    func loadData() {
        
    }
}

// MARK: - Datasources
extension WBRootViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
}

// MARK: - Delegates
extension WBRootViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
}

extension WBRootViewController: WBVisitorViewDelegate {
    func beginlogin() {
        let loginViewController = WBOAuthViewController()
        let loginNavigationController = UINavigationController(rootViewController: loginViewController)
        self.present(loginNavigationController, animated: true, completion: nil)
    }
}
